//
//  LGNewNoteDataModel.m
//  LGNewNote_Example
//
//  Created by 刘亚军 on 2020/4/9.
//  Copyright © 2020 lyj. All rights reserved.
//

#import "LGNewNoteDataModel.h"
#import "LGNewNoteManager.h"
#import <MJExtension/MJExtension.h>
#import <YJExtensions/YJExtensions.h>
#import <YJBaseModule/YJBHpple.h>
#import "LGKConst.h"
#import <LGAlertHUD/LGAlertHUD.h>
#import "NSString+Notes.h"
#import "LGKNoteRespondeModel.h"
static CGFloat const LGNewNoteImageOffset = 10.f;
@implementation LGNewNoteDataModel
+ (NSArray *)mj_ignoredPropertyNames{
    return @[@"hash",@"superclass",@"description",@"debugDescription",@"NoteContent_Att",@"imgaeUrls",@"mixTextImage",@"imageAllCont",@"imageInfo",@"UserName",@"UserType",@"TotalCount"];
}
- (instancetype)init{
    if (self = [super init]) {
        _UserID = [LGNewNoteManager defaultManager].UserID;
        _UserName = [LGNewNoteManager defaultManager].UserName;
        _UserType = [LGNewNoteManager defaultManager].UserType;
        _SchoolID = [LGNewNoteManager defaultManager].SchoolID;
        _NoteTitle = [LGNewNoteManager defaultManager].NoteTitle;
        _ResourceName = [LGNewNoteManager defaultManager].ReSourceName;
        _ResourceID = [LGNewNoteManager defaultManager].ResourceID;
        _SysID = [LGNewNoteManager defaultManager].SystemID;
        _MaterialName = [LGNewNoteManager defaultManager].MaterialName;
        _MaterialID = [LGNewNoteManager defaultManager].MaterialID;
        
        if ([LGNewNoteManager defaultManager].NoteContent && [LGNewNoteManager defaultManager].NoteContent.length > 0) {
            _NoteContent = [LGNewNoteManager defaultManager].NoteContent;
            _NoteContent_Att = [LGNewNoteManager defaultManager].NoteContent.lg_adjustImageHTMLFrame.lg_changeforMutableAtttrubiteString;
            [self saveImageInfoInAttr:_NoteContent_Att];
            [LGNewNoteManager defaultManager].NoteContent = @"";
        }
    }
    return self;
}
NSString *LGNewNoteIsStrEmpty(NSString *string){
    if (string && string.length > 0) {
        return string;
    }
    return @"";
}
- (void)uploadNoteDataWithComplete:(void (^)(BOOL))complete{
    [self uploadNoteInfoWithComplete:complete];
}

- (void)uploadNoteInfoWithComplete:(void (^)(BOOL))complete{
    NSString *url = [[LGNewNoteManager defaultManager].NoteApi yj_stringByAppendingPathComponent:[NSString stringWithFormat:@"api/Note/SavePerNote?UserID=%@&Token=%@",LGNewNoteManager.defaultManager.UserID,LGNewNoteManager.defaultManager.Token]];
    
    NSDictionary *params = [self mj_JSONObject];
    [[YJNetManager defaultManager].setRequest(url).setRequestType(YJRequestTypePOST).setParameters(params) startRequestWithSuccess:^(id  _Nonnull response) {
        LGKNoteRespondeModel *resModel = [LGKNoteRespondeModel responseModelWithData:response];
        if (resModel.isSuccess) {
            if (complete) {
                complete(YES);
            }
        }else{
            if (complete) {
                complete(NO);
            }
        }
    } failure:^(NSError * _Nonnull error) {
        if (complete) {
            complete(NO);
        }
    }];
}
- (void)uploadNoteImg:(UIImage *)image complete:(void (^)(NSString * _Nullable))complete{
    [LGAlert showIndeterminateWithStatus:@"图片上传..."];
    NSString *url = [[LGNewNoteManager defaultManager].NoteApi stringByAppendingString:@"api/Note/UploadImg"];
    YJUploadModel *uploadModel = [[YJUploadModel alloc] init];
    NSMutableArray *imageDatas = [NSMutableArray array];
    NSMutableArray *fileNames = [NSMutableArray array];
    [fileNames addObject:[NSString stringWithFormat:@"%@%li.png",[[NSUUID UUID] UUIDString],imageDatas.count]];
    NSData *imgData = [[UIImage yj_fixOrientation:image] yj_compressImageOnlength:200];
    [imageDatas addObject:imgData];
    uploadModel.uploadDatas = imageDatas;;
    uploadModel.name = @"file";
    uploadModel.fileNames = fileNames;
    uploadModel.fileType = @"image/png";

    [[YJNetManager defaultManager].setRequest(url).setRequestType(YJRequestTypeUpload).setUploadModel(uploadModel) startRequestWithProgress:^(NSProgress *progress) {
        NSLog(@"图片上传进度:%@",@(progress.fractionCompleted));
    } success:^(id response) {
        NSLog(@"成功：%@",response);
        LGKNoteRespondeModel *resModel = [LGKNoteRespondeModel responseModelWithData:response];
        if (resModel.isSuccess && !IsArrEmpty(resModel.Data)) {
            [LGAlert showIndeterminateWithStatus:@"图片加载..."];
            NSArray *imagesUrls = resModel.Data;
            if (complete) {
                complete(imagesUrls.firstObject);
            }
        }else{
            [LGAlert showSuccessWithStatus:@"上传失败"];
            if (complete) {
                complete(nil);
            }
        }
    } failure:^(NSError *error) {
        [LGAlert showSuccessWithStatus:@"上传失败"];
        if (complete) {
            complete(nil);
        }
    }];
}

- (NSMutableDictionary *)imageInfo{
    if (!_imageInfo) {
        _imageInfo = [NSMutableDictionary dictionary];
    }
    return _imageInfo;
}

- (void)saveImageInfoInAttr:(NSAttributedString *) attr{
    NSString *html = [self deleteBodyInAttr:attr];
    NSArray *textImgArr = [self imageArrayInHTML:self.NoteContent];
    NSArray *bodyImgArr = [self imageArrayInHTML:html];
    if (bodyImgArr && bodyImgArr.count > 0) {
        for (int i = 0; i < bodyImgArr.count; i++) {
            YJBHppleElement *textHppleElement = textImgArr[i];
            YJBHppleElement *bodyHppleElement = bodyImgArr[i];
            [self.imageInfo setObject:textHppleElement.attributes forKey:[bodyHppleElement.attributes objectForKey:@"src"]];
        }
    }
}
- (void)updateImageInfo:(NSDictionary *) imageInfo imageAttr:(NSAttributedString *) imageAttr{
    NSString *html = [self deleteBodyInAttr:imageAttr];
    NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];
    YJBHpple *xpathParser = [[YJBHpple alloc] initWithHTMLData:htmlData];
    NSArray *imgArray = [xpathParser searchWithXPathQuery:@"//img"];
    if (imgArray && imgArray.count > 0) {
        YJBHppleElement *hppleElement = imgArray.firstObject;
        NSDictionary *attributes = hppleElement.attributes;
        NSString *src = [attributes objectForKey:@"src"];
        [self.imageInfo setObject:imageInfo forKey:src];
    }
}

// 图片
- (NSArray *)imageArrayInHTML:(NSString *)html{
    NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];
    YJBHpple *tfh = [[YJBHpple alloc] initWithHTMLData:htmlData];
    NSArray *imageArray = [tfh searchWithXPathQuery:@"//img"];
    return imageArray;
}

- (NSString *)deleteBodyInAttr:(NSAttributedString *) attr{
    NSString *html = nil;
    if (attr && attr.length > 0) {
        
        NSDictionary *exportParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
        
        NSData *htmlData = [attr dataFromRange:NSMakeRange(0,attr.length) documentAttributes:exportParams error:nil];
        
        YJBHpple *xpathParser = [[YJBHpple alloc] initWithHTMLData:htmlData];
        NSArray *bodyArray = [xpathParser searchWithXPathQuery:@"//body"];
        if (bodyArray && bodyArray.count > 0) {
            YJBHppleElement *hppleElement = bodyArray.firstObject;
            html = hppleElement.raw;

            html = [html stringByReplacingOccurrencesOfString:@"<body>\n" withString:@""];
            html = [html stringByReplacingOccurrencesOfString:@"\n</body>" withString:@""];
           
           
            
            
        }
    }
    return html;
}

- (void)updateText:(NSAttributedString *)textAttr{
    NSString *html = [self deleteBodyInAttr:textAttr];
    NSArray *textImgArr = [self imageArrayInHTML:html];
    
     _imageAllCont = textImgArr.count;
    if (textImgArr && textImgArr.count > 0) {
        for (int i = 0; i < textImgArr.count; i++) {
            YJBHppleElement *hppleElement = textImgArr[i];
            NSDictionary *attrDic = hppleElement.attributes;
            NSString *str1 = [NSString stringWithFormat:@"<img src=\"%@\" alt=\"%@\"/>",attrDic[@"src"],attrDic[@"alt"]];
            NSDictionary *attrDic2 = self.imageInfo[attrDic[@"src"]];
            NSString *width;
            NSString *height;
            CGFloat screenReferW = [UIScreen mainScreen].bounds.size.width - LGNewNoteImageOffset;
            if ([[attrDic2 allKeys] containsObject:@"width"]) {
                width = attrDic2[@"width"];
                height = attrDic2[@"height"];
            } else {
                width = [NSString stringWithFormat:@"%.f",screenReferW];
                height = width;
            }
            NSString *str2 = [NSString stringWithFormat:@"<img class=\"myInsertImg\" src=\"%@\" width=\"%@\" height=\"%@\"/>",attrDic2[@"src"],width,height];
            html = [html stringByReplacingOccurrencesOfString:str1 withString:str2];
        }
    }
    
    _NoteContent = html;
}
@end
